package com.atguigu.gmall.boot.redistemplate.service.impl;


import com.atguigu.gmall.boot.redistemplate.pojo.User;
import com.atguigu.gmall.boot.redistemplate.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author 陈昆昆
 * @version 1.0
 * @date 2020/6/10 21:33
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public User getUser(String username, String password) {

        return null;
    }

    @Override
    public Map<String, Object> checkUserKey(String username) {
        String key = User.getcheckKey(username);
        Map<String,Object> map = new HashMap<>();
        if (redisTemplate.hasKey(key)){
            map.put("flag", true);
            Long expire = redisTemplate.getExpire(key, TimeUnit.MINUTES);
            map.put("time",expire);
        }
        map.put("flag",false);
        return map;
    }

    @Override
    public String checkloginCout(String username) {
        String key = User.getcheckcountKey(username);
        int num = 5;
        if (!redisTemplate.hasKey(key)){//3.1如果不存在 是第一次登录失败次数为1 user:loginCount:fail
            redisTemplate.opsForValue().set(key,"1");
            redisTemplate.expire(key,2,TimeUnit.MINUTES);
            return "改用户在2分钟内还可以登录"+(num-1)+"次";
        }else{   //查询登录失败次数的key结果
            int count = Integer.parseInt(redisTemplate.opsForValue().get(key).toString());
            if (count<(num-1)){//user:loginCount:fail+1
                redisTemplate.opsForValue().increment(key,1);
                Long expire = redisTemplate.getExpire(key,TimeUnit.SECONDS);
                return "改用户在"+expire+"秒内还可以登录"+(num-1-count)+"次";
            }else{// 限制登录Key存在，同时设置限制登录时间锁定1小时
                redisTemplate.expire(User.getcheckKey(username), 1, TimeUnit.HOURS);
                return "该用户在规定时间内超出登录限制次数";
            }
        }
    }
}
